/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Database;

import Peer.PeerRequest;
import Peer.pTCP;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.PeerEntity;

/**
 *
 * @author bangyo17
 */
public class TrackerDBHandler {

    private Connection connect = null;
    private Statement statement = null;
    private PreparedStatement preparedStatement = null;
    private ResultSet resultSet = null;
    private String mysqlpass;
    public int portSize = 0;

    public String getMysqlpass() {
        return mysqlpass;
    }

    public void setMysqlpass(String mysqlpass) {
        this.mysqlpass = mysqlpass;
    }

    

    public ArrayList<PeerEntity> HandleRequest(String request) throws Exception {
        //ganti jadi return PORT TCP (jadinya array of array of integer)
        try {

            Class.forName("com.mysql.jdbc.Driver");
            connect = DriverManager.getConnection("jdbc:mysql://localhost/KoTorrent?user=root&password="+this.mysqlpass);


            // check database from request
            //port HTTP
            statement = connect.createStatement();
            resultSet = statement.executeQuery("select * from listpeer WHERE FileName = '" + request + "' ORDER BY complete DESC");
            //port TCP
            //ini query buat tabel port_service
            Statement forTCP = connect.createStatement();
            ResultSet resultTCP;
            //resultTCP = forTCP.executeQuery(request)

            int list[] = new int[50];
            ArrayList<PeerEntity> listPeer = new  ArrayList<PeerEntity>();
            int i = 0;
            while (resultSet.next() && i < 50) {
                //listPeer.add(new PeerEntity(resultSet.getInt("Port")));
                ArrayList<pTCP> pt = new ArrayList<pTCP>();
                ArrayList<String> pts = new ArrayList<String>();
                String[] pecah = resultSet.getString("port_tcp").split(",");

                pts.addAll(Arrays.asList(pecah));
                for (int k=0; k<pts.size(); k++){
                    //pt.add(new pTCP(Integer.parseInt(pts.get(k)),""));
                    listPeer.get(i).portTCP.add(new pTCP(Integer.parseInt(pts.get(k)),""));
                }
                
                i++;
            }
            portSize = i;

            //sekarang cari port TCP
            

            // list[i] adalah list port yang memiliki request
            resultSet.first();

            return listPeer;
            // send list[i] to client

        } catch (Exception e) {
            throw e;
        } finally {
            close();
        }

    }

    public void insertRequest(int port, String filename, int uploaded, int downloaded, int left) throws Exception{
         try {

            Class.forName("com.mysql.jdbc.Driver");
            connect = DriverManager.getConnection("jdbc:mysql://localhost/KoTorrent?user=root&password="+this.mysqlpass);


            // check database from request
            statement = connect.createStatement();
            String query = "INSERT INTO file_stats (port, filename, uploaded, downloaded, left_) VALUES "
                    + "(" + port + ",'" + filename + "' ," + uploaded + "," + downloaded + "," + left + ")";
            int result = statement.executeUpdate(query);
            // System.out.println(query);
            // send list[i] to client

        } catch (Exception e) {
            throw e;
        } finally {
            close();
        }
    }

    public void connect() throws ClassNotFoundException, SQLException{
        Class.forName("com.mysql.jdbc.Driver");
        connect = DriverManager.getConnection("jdbc:mysql://localhost/KoTorrent?user=root&password="+this.mysqlpass);
        statement = connect.createStatement();
    }

    public ArrayList<String> selectPeer(String filename, int com) throws ClassNotFoundException, SQLException{
        ArrayList<String> out = new ArrayList<String>();

        connect();

        resultSet = statement.executeQuery("select * from listpeer WHERE FileName = '" + filename + "' AND complete="+com+" ORDER BY complete DESC");
        int i=0;
        while(resultSet.next()){
            out.add(resultSet.getString("Port"));
            i++;
        }

         return out;
    }

    public void deleteOnePeer(int port) throws ClassNotFoundException, SQLException{
        connect();
        String query = "DELETE FROM listpeer WHERE Port="+port;
        int r = statement.executeUpdate(query);
    }

    public void HandleShareFile(String IP, int Port, String filename, int com) throws Exception {
        try {

            Class.forName("com.mysql.jdbc.Driver");
            connect = DriverManager.getConnection("jdbc:mysql://localhost/KoTorrent?user=root&password="+this.mysqlpass);

            String ptc = "";

//            for(int i=0; i<pTCP.size(); i++){
//                ptc = ptc + pTCP.get(i) + ",";
//            }

            // check database from request
            statement = connect.createStatement();
            int result = statement.executeUpdate("INSERT INTO listpeer (IP, Port, FileName, complete) "
                    + "VALUES ('"+IP+"','"+Port+"','"+filename+"','"+com+"')");


            // send list[i] to client

        } catch (Exception e) {
            throw e;
        } finally {
            close();
        }
    }

    // You need to close the resultSet
    private void close() {
        try {
            if (resultSet != null) {
                resultSet.close();
            }

            if (statement != null) {
                statement.close();
            }

            if (connect != null) {
                connect.close();
            }
        } catch (Exception e) {
        }
    }

}
